package org.sixtynine.stock.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.cache.CurrentShareCache;
import org.sixtynine.stock.cache.SectorCache;
import org.sixtynine.stock.cache.SectorDto;
import org.sixtynine.stock.controller.front.ChartsPage;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.DailySectorData;
import org.sixtynine.stock.entity.IntradaySectorData;
import org.sixtynine.stock.entity.IntradayShareData;
import org.sixtynine.stock.model.ColData;
import org.sixtynine.stock.model.ColModel;
import org.sixtynine.stock.model.GridData;
import org.sixtynine.stock.result.HomeShareResult;
import org.sixtynine.stock.result.Result;
import org.sixtynine.stock.result.Sortable;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.StockManagerService;
import org.sixtynine.stock.service.business.StockUtil;
import org.sixtynine.stock.util.DateUtil;
import org.sixtynine.stock.util.Signal;
import org.sixtynine.stock.util.Signal.SignalType;
import org.sixtynine.stock.util.StockComparator;
import org.sixtynine.stock.util.StockComparator.ShareResultComparator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * controller for the home
 * 
 * @author Thilanka
 * 
 */
@Controller
public class HomeController extends AbstractFrontController implements
		ChartsPage {

	@Autowired
	CurrentShareCache currentShareCache;

	@Autowired
	private StockManagerService service;

	@Autowired
	private GenericService genericService;

	/** TODO set is from config */
	private int resultsPerPage = 10;

	private static final Logger logger = Logger.getLogger(HomeController.class);

	@RequestMapping(value = "/")
	public ModelAndView mainPage(HttpServletRequest request) {
		return makeHome(request);
	}

	@RequestMapping(value = "/asicharts", method = RequestMethod.GET)
	@ResponseBody
	public String getSectorData(
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "timeRange", required = false) String timeRange)
			throws ExecutionException {

		if (code.equalsIgnoreCase(Constants.SECTOR_ASI)) {
			code = Constants.SECTOR_ASI;
		} else {
			code = Constants.SECTOR_SNP;
		}

		SectorCache sectorCache = new SectorCache();
		SectorDto asiSector = sectorCache.get(Constants.SECTOR_CACHED_DATA,
				code);
		if (asiSector == null) {
			return "";
		}

		StringBuilder data = new StringBuilder();
		if (timeRange != null && timeRange.equals(TIME_RANGE_INTRADAY)) {
			List<IntradaySectorData> intradaySectorDatas = currentShareCache
					.getDailySector(code);

			if (intradaySectorDatas == null) {
				return "";
			}

			Collections.sort(intradaySectorDatas,
					(Comparator<IntradaySectorData>) StockComparator
							.getInstance(
									StockComparator.INTRADAY_SECTOR_TIME_CMP,
									null));

			data.append("[");
			// iterate from other way round
			for (int i = (intradaySectorDatas.size() - 1); i >= 0; i--) {
				IntradaySectorData intradaySectorData = (IntradaySectorData) intradaySectorDatas
						.get(i);
				data.append("[").append(
						intradaySectorData.getDateTime().getTime());

				data.append(DATA_SEPERATOR).append(
						intradaySectorData.getValue());

				data.append("]");
				data.append(DATA_SEPERATOR);
			}
			if (data.indexOf(DATA_SEPERATOR) > 0) {
				data.deleteCharAt(data.lastIndexOf(DATA_SEPERATOR));
			}
			data.append("]");

		} else {
			List<BaseEntity> dailyList = asiSector.getDailySectorData();
			if (dailyList.size() <= 0) {
				return "";
			}

			data.append("[");
			// iterate from other way round
			for (int i = (dailyList.size() - 1); i >= 0; i--) {
				DailySectorData dailySectorData = (DailySectorData) dailyList
						.get(i);

				data.append("[").append(dailySectorData.getDate().getTime());

				data.append(DATA_SEPERATOR).append(
						dailySectorData.getClosingValue());
				data.append("]");
				data.append(DATA_SEPERATOR);
			}
			if (data.indexOf(DATA_SEPERATOR) > 0) {
				data.deleteCharAt(data.lastIndexOf(DATA_SEPERATOR));
			}
			data.append("]");
		}

		return data.toString();

	}

	@RequestMapping(value = "/index")
	public ModelAndView indexPage(HttpServletRequest request) {
		logger.info("################# Home Page");
		return makeHome(request);
	}

	public ModelAndView makeHome(HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("home");

		showBannar(modelAndView);

		// TODO check
		/*
		 * if (! currentShareCache.isBeforeMarketOpen() &&
		 * DateUtil.isSameDay(currentShareCache.getLastDeletedDate(), new
		 * Date())) {
		 */

		int totalRecords = currentShareCache.getNumOfGainers()
				+ currentShareCache.getNumOfLoosers()
				+ currentShareCache.getNumOfUnchanged();
		if (totalRecords == 0) {
			totalRecords = 1;
		}
		modelAndView.addObject("noOfGainers",
				currentShareCache.getNumOfGainers());
		modelAndView.addObject("noOfLoosers",
				currentShareCache.getNumOfLoosers());
		modelAndView.addObject("noOfUnchanged",
				currentShareCache.getNumOfUnchanged());

		modelAndView
				.addObject(
						"noOfGainersPre",
						getPercentage(totalRecords,
								currentShareCache.getNumOfGainers()));
		modelAndView
				.addObject(
						"noOfLoosersPre",
						getPercentage(totalRecords,
								currentShareCache.getNumOfLoosers()));
		modelAndView.addObject(
				"noOfUnchangedPre",
				(100 - (getPercentage(totalRecords,
						currentShareCache.getNumOfLoosers()) + getPercentage(
						totalRecords, currentShareCache.getNumOfGainers()))));

		// }

		try {
			setSectorSummary(modelAndView);
		} catch (ExecutionException e) {
			logger.error(e.getMessage());
		}
		return modelAndView;
	}

	public List<IntradayShareData> arrangeCompanyData(int type) {
		// we have to load all data and then sort
		Collection<IntradayShareData> intradayShareDatas = (Collection<IntradayShareData>) currentShareCache
				.getShareData();

		List<IntradayShareData> newList = new ArrayList<IntradayShareData>();
		for (IntradayShareData intradayShareData : intradayShareDatas) {
			if (type == StockComparator.TOP_GAINER) {
				if (intradayShareData.getPercentageChange() > 0) {
					newList.add(intradayShareData);
				}
			} else if (type == StockComparator.TOP_LOOSER) {
				if (intradayShareData.getPercentageChange() < 0) {
					newList.add(intradayShareData);
				}
			} else {
				newList.add(intradayShareData);
			}

		}

		Collections.sort(newList,
				(Comparator<IntradayShareData>) StockComparator.getInstance(
						type, null));

		return newList;

	}

	public List<IntradayShareData> arrangeLargeCapCompanyData() {
		// we have to load all data and then sort
		Collection<IntradayShareData> intradayShareDatas = (Collection<IntradayShareData>) currentShareCache
				.getShareData();

		List<IntradayShareData> newList = new ArrayList<IntradayShareData>();
		for (IntradayShareData intradayShareData : intradayShareDatas) {
			newList.add(intradayShareData);
		}

		return newList;

	}

	private GridData<HomeShareResult> getLargeCapData(int page, int rows) {

		GridData<HomeShareResult> gridData = new GridData<HomeShareResult>();

		if (currentShareCache != null
				&& currentShareCache.getLastDeletedDate() != null) {

			if (currentShareCache.isBeforeMarketOpen()
					&& !DateUtil.isSameDay(
							currentShareCache.getLastDeletedDate(), new Date())) {
				return gridData;
			}

			List<IntradayShareData> results = arrangeLargeCapCompanyData();

			// here a do a mapping to HomeShareResult
			List<HomeShareResult> homeResults = getLargeCapShareData(results);

			int startIndex = (page - 1) * rows;
			int endIndex = startIndex + rows;
			endIndex = endIndex > homeResults.size() ? homeResults.size()
					: endIndex;

			gridData.setData(homeResults);
			gridData.setPage(page);

			int totalPages = (homeResults.size() / resultsPerPage) + 1;
			gridData.setTotal(totalPages);
			gridData.setRecords(homeResults.size());

			return gridData;
		}
		return gridData;
	}

	public List<HomeShareResult> getLargeCapShareData(
			List<IntradayShareData> results) {

		List<HomeShareResult> homeShareResults = new ArrayList<HomeShareResult>();

		for (IntradayShareData intradayShareData : results) {
			if (intradayShareData.getCompany().getLargeCap() == false) {
				continue;
			}

			HomeShareResult homeShareResult = new HomeShareResult();
			homeShareResult.setTicker(intradayShareData.getCompany().getCode());
			homeShareResult.setCompanyName(intradayShareData.getCompany()
					.getName());
			homeShareResult.setSector(intradayShareData.getCompany()
					.getSector().getCode());
			homeShareResult.setSharePrice(intradayShareData
					.getLastTradedPrice());
			homeShareResult.setVolume((int) intradayShareData.getShareVolume());
			homeShareResult.setTurenOver(intradayShareData.getTurnover());
			homeShareResult.setChange(intradayShareData.getValueChange());
			homeShareResult.setChangePresentage(intradayShareData
					.getPercentageChange());
			homeShareResult.setNoOfShares((int) intradayShareData
					.getTradeVolume());

			homeShareResults.add(homeShareResult);

		}

		return homeShareResults;
	}

	/**
	 * TODO similarly set the S&P details
	 * 
	 * @param modelAndView
	 * @throws ExecutionException
	 */
	private void setSectorSummary(ModelAndView modelAndView)
			throws ExecutionException {
		IntradaySectorData asiIntraday = currentShareCache
				.getCurrentSector(Constants.SECTOR_ASI);
		modelAndView.addObject("currentAsi",
				(asiIntraday != null) ? (asiIntraday.getValue()) : 0);
		modelAndView.addObject("asiValueChange",
				(asiIntraday != null) ? (asiIntraday.getValueChange()) : 0);
		modelAndView
				.addObject(
						"asiChangePercent",
						(asiIntraday != null) ? (asiIntraday
								.getPercentageChange()) : 0);

		IntradaySectorData snpIntraday = currentShareCache
				.getCurrentSector(Constants.SECTOR_SNP);
		modelAndView.addObject("currentSnp",
				(snpIntraday != null) ? snpIntraday.getValue() : 0);
		modelAndView.addObject("snpValueChange",
				(snpIntraday != null) ? snpIntraday.getValueChange() : 0);
		modelAndView.addObject("snpChangePercent",
				(snpIntraday != null) ? snpIntraday.getPercentageChange() : 0);

		modelAndView.addObject("totalMktVolume",
				currentShareCache.getTotalMarketVolume());
		modelAndView.addObject("totalTurnOver",
				currentShareCache.getTotalTurnOver());

	}

	/**
	 * @param total
	 * @param individual
	 * @return
	 */
	private int getPercentage(float total, float individual) {
		return (int) (((individual * 100) / total));
	}

	@RequestMapping(value = "/home_components/topgainer")
	public ModelAndView showTopGainer() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/topgainer");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/topgainer/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord,
			HttpServletRequest request) {

		return getIntradayData(page, rows, sidx, sord,
				StockComparator.TOP_GAINER);
	}

	private GridData<HomeShareResult> getIntradayData(int page, int rows,
			String sidx, String sord, int type) {

		GridData<HomeShareResult> gridData = new GridData<HomeShareResult>();

		if (currentShareCache != null
				&& currentShareCache.getLastDeletedDate() != null) {
			// if market is closed. We don't need to display this data
			// its a new day, and market is still not open
			if (currentShareCache.isBeforeMarketOpen()
					&& !DateUtil.isSameDay(
							currentShareCache.getLastDeletedDate(), new Date())) {
				return gridData;
			}
			// ------

			List<IntradayShareData> results = arrangeCompanyData(type);
			if (results.size() <= 0) {
				return gridData;
			}

			// here a do a mapping to HomeShareResult
			List<HomeShareResult> homeResults = getHomeShareData(results);

			if (!StringUtils.isEmpty(sidx) && !StringUtils.isEmpty(sord)) {
				Sortable sortable = new Sortable(sidx, sord);
				ShareResultComparator<Result> comparator = (ShareResultComparator<Result>) StockComparator
						.getInstance(StockComparator.SHARE_RESULT_COMPARATOR,
								sortable);
				comparator.setSortable(sortable);

				Collections.sort(homeResults, comparator);
			}

			int startIndex = (page - 1) * rows;
			int endIndex = startIndex + rows;
			endIndex = endIndex > homeResults.size() ? homeResults.size()
					: endIndex;

			gridData.setData(homeResults.subList(startIndex, endIndex));
			gridData.setPage(page);

			int totalPages = (homeResults.size() / resultsPerPage) + 1;
			gridData.setTotal(totalPages);
			gridData.setRecords(homeResults.size());

			return gridData;
		}
		return gridData;
	}

	public List<HomeShareResult> getHomeShareData(
			List<IntradayShareData> results) {

		List<HomeShareResult> homeShareResults = new ArrayList<HomeShareResult>();
		for (IntradayShareData intradayShareData : results) {
			HomeShareResult homeShareResult = new HomeShareResult();

			homeShareResult.setTicker(intradayShareData.getCompany().getCode());
			homeShareResult.setCompanyName(intradayShareData.getCompany()
					.getName());
			homeShareResult.setSector(intradayShareData.getCompany()
					.getSector().getCode());
			homeShareResult.setSharePrice(intradayShareData
					.getLastTradedPrice());
			homeShareResult.setVolume((int) intradayShareData.getShareVolume());
			homeShareResult.setTurenOver(intradayShareData.getTurnover());
			homeShareResult.setChange(intradayShareData.getValueChange());
			homeShareResult.setChangePresentage(intradayShareData
					.getPercentageChange());
			homeShareResult.setNoOfShares((int) intradayShareData
					.getTradeVolume());
			homeShareResult.setOneDayVolatality(StockUtil
					.calculateOneDayVolatality(intradayShareData));

			homeShareResults.add(homeShareResult);
		}

		return homeShareResults;
	}

	private GridData<HomeShareResult> getSignalsData(int page, int rows,
			SignalType type) {

		GridData<HomeShareResult> gridData = new GridData<HomeShareResult>();
		if (currentShareCache != null
				&& currentShareCache.getLastDeletedDate() != null) {
			if (currentShareCache.isBeforeMarketOpen()
					&& !DateUtil.isSameDay(
							currentShareCache.getLastDeletedDate(), new Date())) {
				return gridData;
			}

			List<Signal> results = currentShareCache.getSignals(type);

			if (results.size() <= 0) {
				return gridData;
			}

			// here a do a mapping to HomeShareResult
			List<HomeShareResult> homeResults = getHomeSignalData(results);

			int startIndex = (page - 1) * rows;
			int endIndex = startIndex + rows;
			endIndex = endIndex > homeResults.size() ? homeResults.size()
					: endIndex;

			gridData.setData(homeResults.subList(startIndex, endIndex));
			gridData.setPage(page);

			int totalPages = (homeResults.size() / resultsPerPage) + 1;
			gridData.setTotal(totalPages);
			gridData.setRecords(homeResults.size());

			return gridData;
		}
		return gridData;

	}

	public List<HomeShareResult> getHomeSignalData(List<Signal> results) {

		List<HomeShareResult> homeShareResults = new ArrayList<HomeShareResult>();

		for (Signal signal : results) {
			HomeShareResult homeShareResult = new HomeShareResult();

			homeShareResult.setTicker(signal.getCompanyCode());
			homeShareResult.setCompanyName(signal.getCompanyName());
			homeShareResult.setSignalChangePr(signal.getChange());
			homeShareResult.setColor(signal.getColor());
			homeShareResult.setSignalType(signal.getType().name());
			homeShareResult.setMessage(signal.getMessage());
			homeShareResult.setSignalVolume(signal.getValue());

			// homeShareResult.setSignalShare(signal.getSharePrice());
			homeShareResult.setTurenOver(signal.getTurnOver());
			homeShareResult.setNoOfShares((int) signal.getNoOfTrade());
			homeShareResult.setValue(signal.getValue());
			homeShareResult.setSharePrice(signal.getSharePrice());
			;

			homeShareResults.add(homeShareResult);
		}

		return homeShareResults;
	}

	private GridData<HomeShareResult> getIntradaySectorData(int page, int rows) {

		GridData<HomeShareResult> gridData = new GridData<HomeShareResult>();
		if (currentShareCache != null
				&& currentShareCache.getLastDeletedDate() != null) {
			if (currentShareCache.isBeforeMarketOpen()
					&& !DateUtil.isSameDay(
							currentShareCache.getLastDeletedDate(), new Date())) {
				return gridData;
			}

			Collection<IntradaySectorData> intradaySectorDatas = (Collection<IntradaySectorData>) currentShareCache
					.getSectorData();

			List<IntradaySectorData> newList = new ArrayList<IntradaySectorData>();
			for (IntradaySectorData intradaySectorData : intradaySectorDatas) {
				newList.add(intradaySectorData);
			}

			// here a do a mapping to HomeShareResult
			List<HomeShareResult> homeResults = getHomeSectorData(newList);

			int startIndex = (page - 1) * rows;
			int endIndex = startIndex + rows;
			endIndex = endIndex > homeResults.size() ? homeResults.size()
					: endIndex;

			gridData.setData(homeResults.subList(startIndex, endIndex));
			gridData.setPage(page);

			int totalPages = (homeResults.size() / resultsPerPage) + 1;

			gridData.setTotal(totalPages);
			gridData.setRecords(homeResults.size());

			return gridData;
		}
		return gridData;
	}

	public List<HomeShareResult> getHomeSectorData(
			List<IntradaySectorData> results) {

		List<HomeShareResult> homeShareResults = new ArrayList<HomeShareResult>();

		for (IntradaySectorData intradaySectorData : results) {
			HomeShareResult homeShareResult = new HomeShareResult();

			homeShareResult.setTicker(intradaySectorData.getSector().getCode());
			homeShareResult.setSector(intradaySectorData.getSector().getName());
			homeShareResult.setValue(intradaySectorData.getValue());
			homeShareResult.setChange(intradaySectorData.getValueChange());
			homeShareResult.setChangePresentage(intradaySectorData
					.getPercentageChange());

			homeShareResults.add(homeShareResult);
		}

		return homeShareResults;
	}

	@RequestMapping(value = "/home_components/topgainer/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getTopGainerColumnData() {
		return getTopGainerColData();
	}

	public ColData getTopGainerColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/toplooser")
	public ModelAndView showTopLooser() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/toplooser");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/toplooser/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getTopLooserData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord,
			HttpServletRequest request) {

		return getIntradayData(page, rows, sidx, sord,
				StockComparator.TOP_LOOSER);
	}

	@RequestMapping(value = "/home_components/toplooser/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getTopLooserColumnData() {
		return getTopLooserColData();
	}

	public ColData getTopLooserColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/hightsturnover")
	public ModelAndView showHightestTurnOver() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/hightsturnover");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/hightsturnover/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getHightTurnOverData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord,
			HttpServletRequest request) {

		return getIntradayData(page, rows, sidx, sord,
				StockComparator.HIGHEST_TURNOVER);
	}

	@RequestMapping(value = "/home_components/hightsturnover/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getHightsTurnoverColumnData() {
		return getHightsTurnoverColData();
	}

	public ColData getHightsTurnoverColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/mostactive")
	public ModelAndView showMostActive() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/mostactive");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/mostactive/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getMostActiveData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord,
			HttpServletRequest request) {

		return getIntradayData(page, rows, sidx, sord,
				StockComparator.MOST_ACTIVE);
	}

	@RequestMapping(value = "/home_components/mostactive/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getMostActiveColumnData() {
		return getMostActiveColData();
	}

	public ColData getMostActiveColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/sectorsummary")
	public ModelAndView showSectorSummary() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/sectorsummary");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/sectorsummary/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getSectorSummaryData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getIntradaySectorData(page, rows);
	}

	@RequestMapping(value = "/home_components/sectorsummary/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getSectorSummaryColumnData() {
		return getSectorSummaryColData();
	}

	public ColData getSectorSummaryColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();
		colModels.add(new ColModel("sector"));
		colModels.add(new ColModel("value", "number", "right"));
		colModels.add(new ColModel("change", "number", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Sector Name");
		colNames.add("Index Value");
		colNames.add("Change");
		colNames.add("Presentage changer %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/largecap")
	public ModelAndView showLargeCap() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/largecap");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/largecap/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getLargeCapData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getLargeCapData(page, rows);
	}

	@RequestMapping(value = "/home_components/largecap/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getLargeCapColumnData() {
		return getLargeCapColData();
	}

	public ColData getLargeCapColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/high")
	public ModelAndView showHigh() {
		ModelAndView modelAndView = new ModelAndView("/home_components/high");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/high/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getHighSignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.HIGH);
	}

	@RequestMapping(value = "/home_components/high/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getHighColumnData() {
		return getHighColData();
	}

	public ColData getHighColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/low")
	public ModelAndView showLow() {
		ModelAndView modelAndView = new ModelAndView("/home_components/low");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/low/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getLowSignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.LOW);
	}

	@RequestMapping(value = "/home_components/low/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getLowColumnData() {
		return getLowColData();
	}

	public ColData getLowColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();
		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/over_bought")
	public ModelAndView showOverBought() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/over_bought");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/over_bought/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getOverBoughtSignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.RSI_OVERBOUGHT);
	}

	@RequestMapping(value = "/home_components/over_bought/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getOverBoughtColumnData() {
		return getOverBoughtColData();
	}

	public ColData getOverBoughtColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/over_sold")
	public ModelAndView showOverSold() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/over_sold");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/over_sold/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getOverSoldSignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.RSI_OVERSOLD);
	}

	@RequestMapping(value = "/home_components/over_sold/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getOverSoldColumnData() {
		return getOverSoldColData();
	}

	public ColData getOverSoldColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/most_volatality")
	public ModelAndView showMosVolatality() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/most_volatality");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/most_volatality/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getMostVolatalitySignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord,
			HttpServletRequest request) {

		return getIntradayData(page, rows, sidx, sord,
				StockComparator.MOST_VOLATALITY);
	}

	@RequestMapping(value = "/home_components/most_volatality/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getMostVolatalityColumnData() {
		return getMostVolatalityColData();
	}

	public ColData getMostVolatalityColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("volume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("changePresentage", "number", "right"));
		colModels.add(new ColModel("oneDayVolatality", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trade");
		colNames.add("Change %");
		colNames.add("1D Volatality %");
		colData.setColNames(colNames);
		return colData;
	}

	@RequestMapping(value = "/home_components/unusal_volume")
	public ModelAndView showUnusalVolume() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/unusal_volume");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/unusal_volume/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getUnusualVolumeSignalData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.UNUSUAL_VOLUME);
	}

	@RequestMapping(value = "/home_components/unusal_volume/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getUnusualVolumeColumnData() {
		return getUnusualVolumeColData();
	}

	public ColData getUnusualVolumeColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colData.setColNames(colNames);
		return colData;
	}

	/** Sma 20 crossing */

	@RequestMapping(value = "/home_components/sma20_crossing")
	public ModelAndView showSma20Crossing() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/sma20_crossing");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/sma20_crossing/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getSma20CrossingData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.SMA20_CROSSING);
	}

	@RequestMapping(value = "/home_components/sma20_crossing/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getSma20CrossingColumnData() {
		return getSma20CrossingColData();
	}

	public ColData getSma20CrossingColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colModels.add(new ColModel("color", true));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colNames.add("Color");
		colData.setColNames(colNames);
		return colData;
	}

	/** Sma 50 crossing */
	@RequestMapping(value = "/home_components/sma50_crossing")
	public ModelAndView showSma50Crossing() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/sma50_crossing");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/sma50_crossing/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getSma50CrossingData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.SMA50_CROSSING);
	}

	@RequestMapping(value = "/home_components/sma50_crossing/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getSma50CrossingColumnData() {
		return getSma50CrossingColData();
	}

	public ColData getSma50CrossingColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colModels.add(new ColModel("color", true));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colNames.add("Color");
		colData.setColNames(colNames);
		return colData;
	}

	/** Sma 10 crossing */
	@RequestMapping(value = "/home_components/sma10_crossing")
	public ModelAndView showSma10Crossing() {
		ModelAndView modelAndView = new ModelAndView(
				"/home_components/sma10_crossing");

		return modelAndView;
	}

	@RequestMapping(value = "/home_components/sma10_crossing/list", method = RequestMethod.POST)
	@ResponseBody
	public GridData getSma10CrossingData(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false) Integer rows,
			HttpServletRequest request) {

		return getSignalsData(page, rows, SignalType.SMA10_CROSSING);
	}

	@RequestMapping(value = "/home_components/sma10_crossing/colData", method = RequestMethod.GET)
	@ResponseBody
	public ColData getSma10CrossingColumnData() {
		return getSma50CrossingColData();
	}

	public ColData getSma10CrossingColData() {
		ColData colData = new ColData();

		List<ColModel> colModels = new ArrayList<ColModel>();

		colModels.add(new ColModel("ticker"));
		colModels.add(new ColModel("companyName"));
		colModels.add(new ColModel("sharePrice", "number", "right"));
		colModels.add(new ColModel("turenOver", "integer", "right"));
		colModels.add(new ColModel("signalVolume", "integer", "right"));
		colModels.add(new ColModel("noOfShares", "integer", "right"));
		colModels.add(new ColModel("signalChangePr", "number", "right"));
		colModels.add(new ColModel("color", true));
		colData.setColModel(colModels);

		List<String> colNames = new ArrayList<String>();

		colNames.add("Ticker");
		colNames.add("Company Name");
		colNames.add("Share Price(LKR)");
		colNames.add("Turnover");
		colNames.add("Volume");
		colNames.add("No of Trades");
		colNames.add("Change %");
		colNames.add("Color");
		colData.setColNames(colNames);
		return colData;
	}

	public int getResultsPerPage() {
		return resultsPerPage;
	}

	public void setResultsPerPage(int resultsPerPage) {
		this.resultsPerPage = resultsPerPage;
	}

}
